package com.cauli.utils.handler;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author Cauli
 * @date 2022/12/15 16:46
 * @description Mybatis-Plus 配置拦截器
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    /**
     * Mybatis-Plus执行添加操作，这个方法执行
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        this.autoFillCharacter("creatorId",metaObject);
        this.autoFillCharacter("updaterId",metaObject);
        this.autoFillTime("createTime",metaObject);
        this.autoFillTime("updateTime",metaObject);
    }

    /**
     * Mybatis-Plus执行修改操作，这个方法执行
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        this.autoFillCharacter("updaterId", metaObject);
        this.autoFillTime("updateTime", metaObject);
    }

    /**
     * 自动填充创建者ID和更新者ID
     *
     * @param filedName
     * @param metaObject
     */
    private void autoFillCharacter(String filedName, MetaObject metaObject) {
        boolean hasField = metaObject.hasSetter(filedName);
        if (hasField) {
            this.setFieldValByName(filedName, StpUtil.getLoginIdAsLong(), metaObject);
        }
    }

    /**
     * 自动填充创建者ID和更新者ID
     *
     * @param filedName
     * @param metaObject
     */
    private void autoFillTime(String filedName, MetaObject metaObject) {
        boolean hasField = metaObject.hasSetter(filedName);
        if (hasField) {
            this.setFieldValByName(filedName, new Date(), metaObject);
        }
    }
}
